using System;
using System.Data.SqlClient;
using System.Collections.Generic;

using SBPweb.Data;
using System.Data;

#if SQL2005
namespace SBPweb.Data.SQL2005
{

	/// <summary>
	/// This class implements functionallity to create parameterized commands, 
	/// wich are able to read entities from an sql database via stored procedure
	/// </summary>
	public class ReadByParameteredCommandFactory : ISelectionFactory<List<KeyValuePair<string, object>>>
	{

		#region Private fields

		private string mCommandName;

		#endregion

		#region Constructor logic

		/// <summary>
		/// Creates a new ReadByParameteredCommandFactory instance
		/// </summary>
		/// <param name="storedProcCommandName">Name of the stored procedure</param>
		public ReadByParameteredCommandFactory(string storedProcCommandName)
		{
			mCommandName = storedProcCommandName;
		}

		#endregion

		#region ISelectionFactory<List<KeyValuePair<string, object>>> Members

		/// <summary>
		/// This method creates an SqlCommand
		/// </summary>
		/// <param name="db">SqlDatabase db</param>
		/// <param name="parameters">Parameters of the stored procedure</param>
		/// <returns>SqlCommand</returns>
		public SqlCommand ConstructSelectCommand(SqlDatabase db, List<KeyValuePair<string, object>> parameters)
		{
			SqlCommand command = db.GetStoredProcCommand(mCommandName);

			string format = "@{0}";

			foreach (KeyValuePair<string, object> kvp in parameters)
			{
				SqlDbType type = SqlDbType.Int;
				if (kvp.Value != null)
				{
					type = SqlDatabase.GetDbTypeByType(kvp.Value.GetType());
				}
				db.AddInParameter(command, string.Format(format, kvp.Key), type, kvp.Value);
			}

			return command;
		}

		#endregion

		#region IDbToBusinessEntityNameMapper Members

		/// <summary>
		/// This methods maps the stored procedure parameter names to entity property names
		/// </summary>
		/// <param name="dbParameter">Name of the parameter</param>
		/// <returns>Name of the property of the entity</returns>
		public string MapDbParameterToBusinessEntityProperty(string dbParameter)
		{
			return dbParameter;
		}

		#endregion

	}
}
#endif